package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //查询当前用户
        wrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //查询文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //查询频道
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //查询时间范围
        wrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //查询关键字
        wrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //按照发布时间降序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        page(page, wrapper);
        //3,返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1.参数校验
        if (dto == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.发布文章或修改文章
        WmNews wmNews = saveOrUpdateNews(dto);
        //3.如果状态为0,保存为草稿
        if (WmNews.Status.NORMAL.getCode() == dto.getStatus()) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //从内容中提取图片
        List<String> materials = extractUrlInfo(dto.getContent());
        //4.保存文章内容图片和素材的关系
        saveRelativeInfoForContent(wmNews.getId(), materials);
        //5.保存文章封面图片和素材的关系
        saveRelativeInfoForCover(dto, wmNews, materials);

        //调用审核文章
        //autoScanService.autoScanWmNews(wmNews.getId());

        //修改为延迟任务
        wmNewsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 文章上下架
     *
     * @param map
     * @return
     */
    @Override
    public ResponseResult downOrUp(Map<String, Object> map) {
        //参数校验
        if (map == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (map.get("id") != null) {
            //1.查询文章是否存在
            WmNews wmNews = getById((Integer) map.get("id"));
            if (wmNews == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //2.查询文章是否发布
            if (wmNews.getStatus() != (short)9){
                return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
            //3.修改文章的enable
            Integer enable = (Integer) map.get("enable");
            wmNews.setEnable(Short.parseShort(enable.toString()));
            updateById(wmNews);
            kafkaTemplate.send("down_or_up-topic", JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存文章封面图片和素材的关系
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //封面图片
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materials.size();
            if (size >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }

        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            saveRelativeInfo(wmNews.getId(), materials, WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 保存文章内容与图片的关系
     *
     * @param id
     * @param materials
     */
    private void saveRelativeInfoForContent(Integer id, List<String> materials) {
        saveRelativeInfo(id, materials, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与文章的关系
     *
     * @param id
     * @param materials
     * @param type
     */
    private void saveRelativeInfo(Integer id, List<String> materials, Short type) {
        if (materials == null || materials.size() <= 0) {
            return;
        }
        //去重并查询数据库
        materials = materials.stream().distinct().collect(Collectors.toList());
        List<WmMaterial> dbMaterials = wmMaterialService.list(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
        if (dbMaterials == null || dbMaterials.size() == 0 || dbMaterials.size() != materials.size()) {
            //素材引用失效
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }
        //获取素材id
        List<Integer> materialIdLIst = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        wmNewsMaterialMapper.saveRelations(materialIdLIst, id, type);
    }

    /**
     * 从内容中提取图片
     *
     * @param content
     * @return
     */
    private List<String> extractUrlInfo(String content) {
        ArrayList<String> images = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if ("image".equals(map.get("type"))) {
                images.add((String) map.get("value"));
            }
        }
        return images;
    }

    /**
     * 保存或修改文章
     *
     * @param dto
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        //拷贝属性
        BeanUtils.copyProperties(dto, wmNews);

        //图片处理
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }
        //如果选择自动,值为-1,存储报错,暂时修改为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }

        //设置其它属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setStatus((short) 0);
        wmNews.setSubmitedTime(new Date());

        //提交或者修改
        if (dto.getId() == null) {
            wmNews.setStatus(WemediaConstants.VM_NEWS_SUBMIT);
            save(wmNews);
        } else {
            //删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            wmNews.setStatus(WemediaConstants.VM_NEWS_DRAFT);
            updateById(wmNews);
        }
        return wmNews;
    }
}
